<template>
  <div class="users">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索框区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="success" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表单区域 -->
      <el-table :data="usersList" border style="width: 100%" stripe>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="150"
        ></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 父组件提供模板，子组件提供数据；scope.row 获取当前行数据 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handlechange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="175">
          <template slot-scope="scope">
            <!-- 修改用户信息 -->
            <el-tooltip
              class="item"
              :enterable="false"
              effect="dark"
              content="编辑用户"
              placement="top-start"
            >
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                @click="goEdit(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 删除用户信息 -->
            <el-tooltip
              class="item"
              :enterable="false"
              effect="dark"
              content="删除用户"
              placement="top-start"
            >
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="goDel(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              :enterable="false"
              effect="dark"
              content="分配角色"
              placement="top-start"
            >
              <el-button
                type="warning"
                size="small"
                icon="el-icon-setting"
                @click="goSet(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeCange"
        @current-change="handleCurrentChange"
        :page-num="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        background
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form :model="userInfo" :rules="formRules" ref="usersFormRef">
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="userInfo.username"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model="userInfo.password"
            autocomplete="off"
            clearable
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input
            v-model="userInfo.email"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input
            v-model.number="userInfo.mobile"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="quit('usersFormRef')">取 消</el-button>
        <el-button type="primary" @click="addUsers('usersFormRef')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户" :visible.sync="editVisible">
      <el-form :model="editInfo" ref="editUserRef">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input
            v-model="editInfo.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="editInfo.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth">
          <el-input v-model="editInfo.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser('editUserRef')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setVisible">
      <div>
        <p>当前的用户：{{ setInfo.username }}</p>
        <p>当前的角色：{{ setInfo.role_name }}</p>
        <p>分配新角色:
            <el-select v-model="setInfo.rid" placeholder="请选择">
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
        </p>
      </div>

          

      <div slot="footer" class="dialog-footer">
        <el-button @click="setVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSet">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchcon: "",
      usersList: [],
      // 请求参数
      queryInfo: {
        query: "",
        pagenum: 1, // 当前页数
        pagesize: 2, // 一页展示几条数据
      },
      total: 0,
      newstate: {
        uId: "",
        type: "",
      },
      // 对话框的显示与隐藏
      dialogFormVisible: false,
      editVisible: false,
      setVisible: false,
      // 添加用户信息
      userInfo: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 修改用户信息
      editInfo: {
        id: "",
        username: "",
        email: "",
        mobile: "",
      },
      // 分配角色信息
      setInfo: {
        id: "",
        username: "",
        role_name: "",
        rid: "", // 用户选中的新角色
      },
      // 分配角色对话框的下拉列表
      options: [],
      formLabelWidth: "70px",
      formRules: {
        username: [
          { required: true, message: "请输入用户名" },
          { min: 2, max: 6, message: "长度在2至6个字符之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码" },
          { min: 2, max: 6, message: "长度在2至6个字符之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号" },
          {
            validator: function (rule, value, callback) {
              const reg =
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号"));
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    // 请求数据
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      //   console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.usersList = res.data.users;
      this.total = res.data.total;
    },
    // 状态更新
    async handlechange(info) {
      this.newstate.uId = info.id;
      this.newstate.uId = info.mg_state;
      const { data: res } = await this.$http.put(
        `users/${info.id}/state/${info.mg_state}`,
        this.newstate
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        info.mg_state = !info.mg_state;
        return this.$message.error("更新状态失败");
      }
      this.$message.success("更新状态成功");
    },
    // 添加用户 按钮
    handleClose() {
      this.quit("usersFormRef");
    },
    // 添加用户的取消按钮 功能：清除表单中的数据并关闭表单
    quit(refname) {
      this.$refs[refname].resetFields();
      this.dialogFormVisible = false;
    },
    // 添加用户 -- 确定按钮
    addUsers(refname) {
      // 先对数据进行校验，通过校验发送 axios 请求
      this.$refs[refname].validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.userInfo);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.quit("usersFormRef");
        this.getUsersList(); // 重新渲染表单
        this.$message.success("成功添加新用户!!!");
      });
    },
    // 修改用户信息
    goEdit(obj) {
      for (var key in this.editInfo) {
        this.editInfo[key] = obj[key];
      }
      // console.log(this.editInfo);
      // -----这是一条平平无奇的分割线-----
      // this.editInfo.username = obj.username;
      // this.editInfo.email = obj.email;
      // this.editInfo.mobile = obj.mobile;
      this.editVisible = true;
    },
    // 提交修改信息
    editUser(refname) {
      this.$refs[refname].validate(async (valid) => {
        if (!valid) return;
        const props = {
          id: this.editInfo.id,
          email: this.editInfo.email,
          mobile: this.editInfo.mobile,
        };
        const { data: res } = await this.$http.put(`users/${props.id}`, props);
        // console.log(res);
        if (res.meta.status !== 200)
          return this.$message.error("用户信息修改失败~~~");
        this.editVisible = false;
        this.getUsersList();
        this.$message.success("成功修改用户信息!!!");
      });
    },
    // 删除用户信息
    goDel(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`);
          if (res.meta.status !== 200)
            return this.$message.error("用户删除失败~~~");
          this.getUsersList();
          this.$message.success("成功删除用户!!!");
          //   this.$message({
          //         type: 'success',
          //         message: '删除成功!'
          //       });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配角色
    async goSet(obj) {
      // 获取 setInfo 当前值， rid = undefined
      for (var key in this.setInfo) {
        this.setInfo[key] = obj[key];
      }
      // 将角色渲染到下拉列表
      this.options = []; // 重新赋值清空，要不然上一次的值存在，下一次才重新请求。会重复，而 id 值是唯一的，这也就是为什么会报错：Duplicate keys detected: '30'. This may cause an update error.
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return;
      res.data.forEach((item) => {
        const ops = {
          value: item.id,
          label: item.roleName,
        };
        this.options.push(ops);
      });

      this.setVisible = true;
    },
    // 提交新分配角色
    async handleSet() {
      if (!this.setInfo.rid) return this.$message.error("请选择角色~~~"); // 下拉列表不能为空
      const setProps = {
        id: this.setInfo.id,
        rid: this.setInfo.rid,
      };
      const { data: res } = await this.$http.put(
        `users/${setProps.id}/role`,
        setProps
      );
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("分配新角色失败~~~");
      this.setVisible = false;
      this.getUsersList();
      this.$message.success("成功设置新角色");
    },
    // 一页展示几条
    handleSizeCange(size) {
      // console.log(size);
      this.queryInfo.pagesize = size;
      this.getUsersList();
    },
    // 当前页数
    handleCurrentChange(cur) {
      // console.log(cur);
      this.queryInfo.pagenum = cur;
      this.getUsersList();
    },
  },
};
</script>

<style scoped>
/* 面包屑 */
.el-breadcrumb {
  min-width: 220px;
}

.el-card {
  min-width: 560px;
}
/* 搜索框 */
.el-card .el-row[data-v-1d681f44] {
  margin-bottom: 15px;
}

/* 表单 */
.el-table .el-table-column span[data-v-1d681f44] {
  display: inline-block;
  padding: 0 10px;
  background-color: rgb(158, 60, 60);
}

/* 添加用户遮罩层 */
/* .el-dialog {
    
} */
.el-dialog__wrapper[data-v-1d681f44] {
  min-width: 800px;
}
.el-form {
  /* min-width: 260px; */
  padding: 0 80px 0 50px;
}

.el-dialog p[data-v-1d681f44] {
  line-height: 20px;
}
</style>